package glm

import (
	"chatgpt/ai/chatglm"
	openai2 "chatgpt/ai/openai"
	"chatgpt/helper"
	"chatgpt/helper/code"
	"chatgpt/logq"
	"chatgpt/services/completion"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/slclub/go-tips"
	"time"
)

func CompletionHandle(ctx *gin.Context) {
	question := ctx.Query("q")

	if !completion.CheckQuestion(question) {
		helper.Echo(ctx, int(code.DATA_NIL), "")
		return
	}
	//unafe := ctx.Query("unsafe")
	//if !ai.AppAiEneity.CheckQuestion(question) && !ai.AppAiEneity.Unsafe(question, unafe) {
	//	helper.Echo(ctx, int(code.SUCCESS), "抱歉没有找到与“"+question+"”相关的信息")
	//	return
	//}
	uid := (helper.Uid(ctx))
	queue := completion.Mgr().Get(uid)
	nquestion := question
	if queue != nil {
		//nquestion = queue.ConvPrompt(question)
	}

	//mcode, replay := openai2.RemoteApi(openai2.OPENAI_COMPLETION, nquestion, map[string]string{
	//	"model":  mod,
	//	"smodel": ctx.Query("smodel"),
	//	"stops":  completion.Mgr().StopSequence(uid),
	//	"unsafe": helper.UNSAFE_MOD,
	//})
	//mcode, replay := ai.Completion(ctx, nquestion, map[string]string{
	//	"model":  mod,
	//	"smodel": ctx.Query("smodel"),
	//	"stops":  completion.Mgr().StopSequence(uid),
	//	"unsafe": helper.UNSAFE_MOD,
	//})
	prompt, use_index := chatglm.Search.CustomQuestion(nquestion)
	act_m := map[string]string{
		"key_word": ctx.Query("q"),
		"prompt":   prompt,
	}
	if val := ctx.Query("zhishiku"); val != "" {
		act_m["zhishiku"] = val
	}
	if !use_index {
		fmt.Fprintf(ctx.Writer, "%s", "抱歉您的问题不在理解范围!!!")
		return
	}
	mcode, replay := chatglm.CompletionRemoteString(ctx.Writer, chatglm.GLM_COMPLETION, nquestion, act_m)

	if mcode == code.SUCCESS {
		completion.Mgr().Add(uid, completion.NewDialogue(question, replay.Data.(string)))
	}

	//helper.Echo(ctx, int(mcode), replay.Data)

	gptRecord := &openai2.AppGPT{}

	writeRes := gptRecord.SetRecordLog(map[string]any{
		"timestamp": time.Now().Unix(),
		"userAgent": ctx.GetHeader("User-Agent"),
		"uid":       uid,
		"smodel":    ctx.Query("smodel"),
		"question":  question,
		"answer":    tips.String(replay.Data),
		"ip":        ctx.RemoteIP(),
		"date":      time.Now(),
	})

	if writeRes != true {
		logq.DebugF("HANDLE.COMPLETION uid:%v ip:%v tokens:%v prompt-all:%s", uid, ctx.RemoteIP(), replay.Tokens, writeRes)
	}

	logq.InfoF("HANDLE.COMPLETION uid:%v ip:%v use-index:%v tokens:%v prompt:%s code:%v", uid, ctx.RemoteIP(), use_index, replay.Tokens, question, int(mcode))
	//logq.DebugF("HANDLE.COMPLETION uid:%v ip:%v tokens:%v prompt-all:%s", uid, ctx.RemoteIP(), replay.Tokens, nquestion)
}
